package cn.zhz.privacy.interceptor;


import cn.zhz.privacy.handler.IEncryptDataHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

/**
 * @author ZHZ
 * @date 2021-11-15
 * @apiNote
 */

@Slf4j
@RequiredArgsConstructor
public class CommonInnerInterceptor implements IInnerInterceptor {

    private final List<IEncryptDataHandler> handlerList;

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        if (parameter != null) {
            handlerList.forEach(handler->{
                if(handler.canHandleParameter(parameter.getClass())){
                    log.debug("beforeQuery：{}",parameter);
                    handler.handleParam(parameter);
                    log.debug("beforeQuery after：{}",parameter);
                }
            });
        }
    }

    @Override
    public void beforeUpdate(Object parameter) {
        if (parameter != null) {
            handlerList.forEach(handler->{
                if(handler.canHandleParameter(parameter.getClass())){
                    log.debug("beforeUpdate：{}",parameter);
                    handler.handleParam(parameter);
                    log.debug("beforeUpdate after：{}",parameter);
                }
            });
        }
    }

    @Override
    public void afterQuery(List<Object> resultList) {
            handlerList.forEach(handler->{
                if(handler.canHandleResult(resultList.get(0).getClass())){
                    log.debug("afterQuery：{}",resultList);
                    handler.handleResultList(resultList);
                    log.debug("afterQuery after：{}",resultList);
                }
            });
    }

}
